import { PaginationProps } from '@douyinfe/semi-ui/lib/es/pagination';
import {
  ChangeInfoSorter,
  TablePaginationProps,
} from '@douyinfe/semi-ui/lib/es/table';
import React from 'react';
import { useMemo } from 'react';

export interface IQueryParams {
  sorter: { [key: string]: 'DESC' | 'ASC' | null };
  filter: { [key: string]: any };
  pageNum: number;
  pageSize: number;
}

export function onPageParamsChange(
  {
    pagination,
    sorter,
  }: {
    pagination: TablePaginationProps | undefined;
    sorter: ChangeInfoSorter<any> | undefined;
  },
  setFilterParams: (value: any) => void
) {
  setFilterParams((prev: IQueryParams) => ({
    ...prev,
    pageNum: pagination?.currentPage,
    pageSize: pagination?.pageSize,
    sorter: sorter?.sortOrder
      ? {
          [sorter?.dataIndex ?? sorter?.sorterKey]:
            sorter?.sortOrder === 'ascend' ? 'ASC' : 'DESC',
        }
      : {},
  }));
}

const TablePagination = ({ paginationOpts, children }: any) => {
  const pageProps: PaginationProps = useMemo(
    () => ({
      total: paginationOpts.total,
      currentPage: paginationOpts.queryParams.pageNum,
      pageSize: paginationOpts.queryParams.pageSize,
      pageSizeOpts: paginationOpts.pageSizeOpts,
    }),
    [paginationOpts]
  );
  return <>{children(pageProps)}</>;
};

export default TablePagination;
